<!-- 营业 - 预结 - 弹窗组件 -->
<template>
  <CustomDialog v-model:visible="dialogVisible" top="2vh" curent-class="pre-settlement-dialog">
    <!-- 加载中的骨架屏 -->
    <div v-if="loading" class="flex-col space-y-54 section skeleton-container">
      <el-skeleton :rows="20" animated />
    </div>

    <!-- 加载完成后显示内容 -->
    <div class="flex-col space-y-54 section" v-else-if="!isEmpty(deskDetail)">
      <div class="flex-col">
        <div class="flex-col items-center">
          <span class="text_7">{{ preSettlementInfo.detail?.shopInfo?.shop_name || '' }}</span>
          <span class="text_9">【预结单】</span>
        </div>
        <div class="flex-row justify-between group_14">
          <span class="font_8 text_15">
            桌台：
            <span>{{ computedDeskName }}</span>
          </span>
        </div>
        <div class="flex-row justify-between group_14">
          <span class="font_8 text_15">收银员：</span>
          <span class="font_8 text_16">{{ preSettlementInfo.detail?.clerkName || '' }}</span>
        </div>
        <div class="flex-row group_16 justify-between items-start">
          <div class="font_8 text_20 danhao">
            单号：{{ preSettlementInfo.ticket_id || '' }}(第{{
              preSettlementInfo.detail?.printNum || '1'
            }}次打印）
          </div>
          <div class="font_12 timedesc">
            {{ formatTime(preSettlementInfo.detail?.timeInfo?.printTime) }}
          </div>
        </div>
        <div class="flex-row group_16 justify-between items-center">
          <span class="font_8 text_20">
            时间：{{ preSettlementInfo.detail?.timeInfo?.openDeskTime || '' }}
          </span>
          <span class="font_12 text_22">
            {{ preSettlementInfo.detail?.timeInfo?.timeSlot || '' }}
          </span>
        </div>
        <div class="flex-row group_16 justify-between items-center" :class="{ 'has-member-price': preSettlementInfo.detail?.priceInfo?.is_vip == 1 }">
          <span class="font_8 width-100">菜品名称</span>
          <span class="font_food width-100 font-center">单价</span>
          <span v-if="preSettlementInfo.detail?.priceInfo?.is_vip == 1" class="font_food width-100 font-center">会员价</span>
          <span class="font_food width-100 font-center">数量</span>
          <span class="font_food width-100 font-right">总金额</span>
        </div>
      </div>
      <div class="flex-col group_25 food-list-box">
        <div
          class="good-list-box"
          v-if="dealAssignDataFunction([], preSettlementInfo.detail?.feast_food_list).length > 0"
        >
          <div class="flex-row group_16 justify-between items-center">
            <div class="font_8 width-100">
              <p>酒席</p>
            </div>
            <div class="font_food width-100">
              {{ dealAssignDataFunction(0, preSettlementInfo.detail?.priceInfo?.feastMoney) }}
            </div>
            <div class="font_food width-100" v-if="preSettlementInfo.detail?.priceInfo?.is_vip == 1">
            </div>
            <div class="font_food width-100">
              {{ dealAssignDataFunction(0, preSettlementInfo.detail?.priceInfo?.openNum) }}
              席
            </div>
            <div class="font_food width-100 font-right">
              {{ dealAssignDataFunction(0, preSettlementInfo.detail?.priceInfo?.allFeastMoney) }}
            </div>
          </div>
        </div>
        <div v-for="food in preSettlementInfo.detail?.feast_food_list" :key="food.desk_id">
          <div class="flex-row justify-between food-item">
            <div class="font_8 width-100">{{ (food.is_discount == 1 ? '* ' : '') + food.name }}</div>
            <div class="font_food width-100">{{ food.price || food.money }}</div>
            <div v-if="preSettlementInfo.detail?.priceInfo?.is_vip == 1" class="font_food width-100">{{ food.member_price || food.price || food.money }}</div>
            <div class="font_food width-100">
              {{ food.num }}{{ food.unit }}
              {{ food.desk_num != '1' ? `*${food.desk_num}席` : '' }}
            </div>
            <div class="font_food width-100 font-right">{{ food.total_money }}</div>
          </div>
          <div class="flex-row space-x-12 group_22" v-if="dealFoodSkuDescFun(food)">
            <span class="font_8">({{ dealFoodSkuDescFun(food) }})</span>
          </div>
          <div v-for="data in food.groupInfo" :key="data.goods_id">
            <div class="flex-row justify-between food-item">
              <div class="font_8 width-100">{{ (data.is_discount == 1 ? '* ' : '') + data.name }}</div>
              <div class="font_food width-100">{{ data.price || data.money }}</div>
              <div v-if="preSettlementInfo.detail?.priceInfo?.is_vip == 1" class="font_food width-100">{{ data.member_price || data.price || data.money }}</div>
              <div class="font_food width-100">
                {{ data.num }}{{ data.unit }}
                {{ data.desk_num != '1' ? `*${data.desk_num}席` : '' }}
              </div>
              <div class="font_food width-100 font-right">{{ data.total_money }}</div>
            </div>
          </div>
        </div>
        <div
          style="width: 100%; height: 1px; background-color: #e2e2e2"
          v-if="
            preSettlementInfo.detail?.foodList &&
            preSettlementInfo.detail?.feast_food_list &&
            preSettlementInfo.detail?.foodList.length &&
            preSettlementInfo.detail?.feast_food_list.length
          "
        ></div>
        <div v-for="food in preSettlementInfo.detail?.foodList" :key="food.desk_id">
          <div class="flex-row justify-between food-item">
            <div class="font_8 width-100">{{ (food.is_discount == 1 ? '* ' : '') + food.name }}</div>
            <div class="font_food width-100">{{ food.price || food.money }}</div>
            <div v-if="preSettlementInfo.detail?.priceInfo?.is_vip == 1" class="font_food width-100">{{ food.member_price || food.price || food.money }}</div>
            <div class="font_food width-100">
              {{ food.num }}{{ food.unit }}
              {{ food.desk_num != '1' ? `*${food.desk_num}席` : '' }}
            </div>
            <div class="font_food width-100 font-right">{{ food.total_money }}</div>
          </div>
          <div class="flex-row space-x-12 group_22" v-if="dealFoodSkuDescFun(food)">
            <span class="font_8">({{ dealFoodSkuDescFun(food) }})</span>
          </div>
          <div v-for="data in food.groupInfo" :key="data.goods_id">
            <div class="flex-row justify-between food-item">
              <div class="font_8 width-100">{{ (data.is_discount == 1 ? '* ' : '') + data.name }}</div>
              <div class="font_food width-100">{{ data.price || data.money }}</div>
              <div v-if="preSettlementInfo.detail?.priceInfo?.is_vip == 1" class="font_food width-100">{{ data.member_price || data.price || data.money }}</div>
              <div class="font_food width-100">
                {{ data.num }}{{ data.unit }}
                {{ data.desk_num != '1' ? `*${data.desk_num}席` : '' }}
              </div>
              <div class="font_food width-100 font-right">{{ data.total_money }}</div>
            </div>
          </div>
        </div>
        <div class="flex-row justify-between borderTop1 group_29 marginTop-10">
          <span class="font_8">小计：</span>
          <span class="font_12 text_47">
            {{ preSettlementInfo.detail?.priceInfo?.originMoney || '0.00' }}
          </span>
        </div>
        
        <template v-if="preSettlementInfo.detail?.priceInfo?.backNum && preSettlementInfo.detail?.priceInfo?.backNum > 0">
          <div class="flex-row justify-between group_30">
            <span class="font_8">退菜：</span>
            <span class="font_12 text_51">
              -{{ preSettlementInfo.detail?.priceInfo?.backMoney || '0.00' }}
            </span>
          </div>
        </template>
        
        <template v-if="preSettlementInfo.detail?.priceInfo?.presentMoney && preSettlementInfo.detail?.priceInfo?.presentMoney > 0">
          <div class="flex-row justify-between group_29">
            <span class="font_8">赠送金额：</span>
            <span class="font_12 text_49">
              -{{ preSettlementInfo.detail?.priceInfo?.presentMoney || '0.00' }}
            </span>
          </div>
        </template>
        
        <template v-if="preSettlementInfo.detail?.priceInfo?.memberSubMoney && preSettlementInfo.detail?.priceInfo?.memberSubMoney > 0">
          <div class="flex-row justify-between group_33">
            <span class="font_8">会员优惠：</span>
            <span class="font_12 text_56">
              -{{ preSettlementInfo.detail?.priceInfo?.memberSubMoney || '0.00' }}
            </span>
          </div>
        </template>
        
        <template v-if="preSettlementInfo.detail?.priceInfo?.couponMoney && preSettlementInfo.detail?.priceInfo?.couponMoney > 0">
          <div class="flex-row justify-between group_33">
            <span class="font_8">优惠券：</span>
            <span class="font_12 text_56">
              -{{ preSettlementInfo.detail?.priceInfo?.couponMoney || '0.00' }}
            </span>
          </div>
        </template>
        
        <template v-if="preSettlementInfo.detail?.priceInfo?.pointMoney && preSettlementInfo.detail?.priceInfo?.pointMoney > 0">
          <div class="flex-row justify-between group_33">
            <span class="font_8">积分抵扣：</span>
            <span class="font_12 text_56">
              -{{ preSettlementInfo.detail?.priceInfo?.pointMoney || '0.00' }}
            </span>
          </div>
        </template>
        
        <template v-if="preSettlementInfo.detail?.priceInfo?.reduceMoney && preSettlementInfo.detail?.priceInfo?.reduceMoney > 0">
          <div class="flex-row justify-between group_33">
            <span class="font_8">抹零：</span>
            <span class="font_12 text_56">
              -{{ preSettlementInfo.detail?.priceInfo?.reduceMoney || '0.00' }}
            </span>
          </div>
        </template>
        
        <template v-if="preSettlementInfo.detail?.priceInfo?.discountMoney && preSettlementInfo.detail?.priceInfo?.discountMoney > 0">
          <div class="flex-row justify-between group_32">
            <span class="font_8 text_54">折扣：</span>
            <span class="font_12 text_55">
              -{{ preSettlementInfo.detail?.priceInfo?.discountMoney || '0.00' }}
            </span>
          </div>
        </template>
        
        <template v-if="preSettlementInfo.detail?.priceInfo?.serviceMoney && preSettlementInfo.detail?.priceInfo?.serviceMoney > 0">
          <div class="flex-row justify-between group_33">
            <span class="font_8">服务费：</span>
            <span class="font_12 text_56">
              +{{ preSettlementInfo.detail?.priceInfo?.serviceMoney || '0.00' }}
            </span>
          </div>
        </template>
        
        <div class="flex-row justify-between group_34">
          <span class="font_8">应收合计：</span>
          <span class="font_12 text_59">
            {{ preSettlementInfo.detail?.priceInfo?.payMoney || '0.00' }}
          </span>
        </div>
        <template
          v-if="
            preSettlementInfo.detail?.userInfo && preSettlementInfo.detail?.userInfo?.grade_name
          "
        >
          <div class="flex-row justify-between borderTop1 group_39 marginTop-10">
            <span class="font_8">会员卡号：</span>
            <span class="font_12">{{ preSettlementInfo.detail?.userInfo?.user_id || '' }}</span>
          </div>
          <div class="flex-row justify-between group_39">
            <span class="font_8">会员等级：</span>
            <span class="font_8 text_67" v-if="preSettlementInfo.detail?.userInfo?.grade_name">
              {{ preSettlementInfo.detail?.userInfo?.grade_name }}
            </span>
          </div>
          <div class="flex-row justify-between group_39">
            <span class="font_8">会员姓名：</span>
            <span class="font_8 text_67">
              {{ preSettlementInfo.detail?.userInfo?.real_name || '' }}
            </span>
          </div>
          <div class="flex-row justify-between group_40">
            <span class="font_8">积分账户：</span>
            <span class="font_12 text_68">
              {{ preSettlementInfo.detail?.userInfo?.points || '0' }}
            </span>
          </div>
          <div class="flex-row justify-between group_41">
            <span class="font_8">账户余额：</span>
            <span class="font_12 text_70">
              {{ preSettlementInfo.detail?.userInfo?.balance || '0.00' }}
            </span>
          </div>
        </template>
        <div class="flex-col items-center group_44">
          <div class="text_74">
            餐厅地址：{{ preSettlementInfo.detail?.shopInfo?.address || '' }}
          </div>
          <div class="flex-col items-center text-wrapper_21">
            <span class="font_6 text_75">订座电话：400-0851-123</span>
          </div>
        </div>
      </div>

      <!-- 底部操作区域 -->
      <div class="flex-row justify-center space-x-20 section_18">
        <template v-if="deskDetail.is_lock?.value === 2">
          <!-- <el-button class="disabled-btn" disabled>已预结</el-button> -->
          <el-button class="confirm-btn" :loading="cancelLoading" @click="handleCancel">
            取消预结
          </el-button>
          <el-button class="print-btn" :loading="printLoading" @click="handlePrint">
            打印
          </el-button>
        </template>
        <el-button v-else class="confirm-btn" :loading="confirmLoading" @click="handleConfirm">
          确定预结
        </el-button>
      </div>
    </div>
  </CustomDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElButton, ElSkeleton } from 'element-plus'
// 使用 any 类型避免 TypeScript 错误
import { isEmpty } from '@/utils/toolsValidate'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import { deskOrderDetail } from '@/api/desktop'
import { printerReprint } from '@/api/common'
import { preOrderTicket } from '@/api/user'

interface Props {
  modelValue: boolean
  deskDetail?: any
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
  (e: 'refreshDesk'): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  deskDetail: null
})

const emit = defineEmits<Emits>()

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val)
})

// 预结信息数据接口定义
interface PreSettlementDetail {
  shopInfo: {
    shop_name?: string
    address?: string
  }
  deskList: Array<{
    name: string
    use_num: number
  }>
  priceInfo: {
    feastMoney?: string
    openNum?: string
    allFeastMoney?: string
    originMoney?: string
    presentMoney?: string
    backMoney?: string
    backNum?: string
    discountMoney?: string
    reduceMoney?: string
    serviceMoney?: string
    payMoney?: string
    memberSubMoney?: string
    couponMoney?: string
    pointMoney?: string
    is_vip?: string
  }
  timeInfo: {
    printTime?: string
    openDeskTime?: string
    timeSlot?: string
  }
  userInfo: {
    user_id?: string
    grade_name?: string
    real_name?: string
    points?: string
    balance?: string
  }
  foodList: Array<any>
  feast_food_list: Array<any>
  clerkName?: string
  printNum?: string
}

// 预结信息数据
const preSettlementInfo = ref<any>({
  detail: {
    shopInfo: {},
    deskList: [],
    priceInfo: {},
    timeInfo: {},
    userInfo: {},
    foodList: [],
    feast_food_list: []
  },
  ticket_id: ''
})

// 加载状态
const loading = ref(false)
const cancelLoading = ref(false)
const confirmLoading = ref(false)
const printLoading = ref(false)

// 监听对话框打开状态
watch(
  () => dialogVisible.value,
  val => {
    if (val && props.deskDetail) {
      getPreSettlementInfo()
    }
  },
  { immediate: true }
)

// 计算桌台名称
const computedDeskName = computed(() => {
  let deskNameList: string[] = []
  if (preSettlementInfo.value?.detail?.deskList?.length) {
    deskNameList = preSettlementInfo.value.detail.deskList.map((desk: any) => {
      return `${desk.name}(${desk.use_num}人)`
    })
    return deskNameList.join('、')
  }
  return props.deskDetail?.desk_name || ''
})

// 处理回显菜品的规格信息（做法+口味+部位）
const dealFoodSkuDescFun = (item: any) => {
  if (item?.notes?.length) {
    return item.notes.join('、')
  } else {
    return false
  }
}

// 处理数据
const dealAssignDataFunction = (defaultValue: any, value: any) => {
  if (Array.isArray(value)) {
    return value || []
  }
  return value || defaultValue
}

// 格式化时间
const formatTime = (time: any) => {
  if (!time) return ''
  const date = new Date(time)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  const seconds = date.getSeconds().toString().padStart(2, '0')
  return `${hours}:${minutes}:${seconds}`
}

// 获取预结账单信息
const getPreSettlementInfo = async () => {
  if (!props.deskDetail || !props.deskDetail.id) return

  loading.value = true

  try {
    // 使用 preOrderTicket API 获取预结单信息
    const res = await preOrderTicket({
      record_id: props.deskDetail.id,
      print: 1 // 获取小票，不执行其他操作
    })

    if (res.status === 200 && res.data.detail) {
      preSettlementInfo.value = res.data.detail
    }
  } catch (error) {
    console.error('获取预结账单信息失败:', error)
    ElMessage.error('获取预结账单信息失败')
  } finally {
    loading.value = false
  }
}

// 取消预结
const handleCancel = async () => {
  if (!props.deskDetail || !props.deskDetail.id) return

  if (props.deskDetail.is_lock?.value === 2) {
    try {
      cancelLoading.value = true

      // 调用取消预结API
      const res = await preOrderTicket({
        record_id: props.deskDetail.id,
        actionType: 'cancel' // 取消预结操作
      })

      if (res.status === 200) {
        ElMessage.success('操作成功')
        emit('success')
        emit('refreshDesk')
        dialogVisible.value = false
      }
    } catch (error) {
      console.error('取消预结失败:', error)
      ElMessage.error('取消预结失败')
    } finally {
      cancelLoading.value = false
    }
  } else {
    dialogVisible.value = false
  }
}

// 确定预结
const handleConfirm = async () => {
  if (!props.deskDetail || !props.deskDetail.id) return

  try {
    confirmLoading.value = true

    // 调用确认预结API
    const res = await preOrderTicket({
      record_id: props.deskDetail.id,
      actionType: 'comfirm', // 确定预结操作
      isPrint: 0
    })

    if (res.status === 200) {
      ElMessage.success('操作成功')
      emit('success')
      emit('refreshDesk') 
      dialogVisible.value = false
    }
  } catch (error) {
    console.error('确认预结失败:', error)
    ElMessage.error('确认预结失败')
  } finally {
    confirmLoading.value = false
  }
}

// 打印预结单
const handlePrint = async () => {
  if (!preSettlementInfo.value?.ticket_id) return

  try {
    printLoading.value = true

    const res = await printerReprint({
      ticket_id: preSettlementInfo.value.ticket_id
    })

    if (res.status === 200) {
      ElMessage.success('推送打印成功')
    }
  } catch (error) {
    console.error('打印失败:', error)
    ElMessage.error('打印失败')
  } finally {
    printLoading.value = false
  }
}
</script>

<style scoped>
.flex-row {
  display: flex;
  flex-direction: row;
}

.flex-col {
  display: flex;
  flex-direction: column;
}

.justify-start {
  justify-content: flex-start;
}

.justify-center {
  justify-content: center;
}

.justify-end {
  justify-content: flex-end;
}

.justify-evenly {
  justify-content: space-evenly;
}

.justify-around {
  justify-content: space-around;
}

.justify-between {
  justify-content: space-between;
}

.items-start {
  align-items: flex-start;
}

.items-center {
  align-items: center;
}

.items-end {
  align-items: flex-end;
}

.section {
  width: 546px;
  /* background: #ffffff; */
  border-radius: 20px;
  /* box-shadow: 3px 0px 24px 0px rgba(0, 0, 0, 0.16); */
  box-sizing: border-box;
  transition: all 1s;
}

.space-y-20 > *:not(:first-child) {
  margin-top: 20px;
}

.text_7 {
  align-self: center;
  color: #333333;
  font-size: 20px;
  font-family: PingFang SC Bold;
  font-weight: 700;
}

.text_9 {
  margin-top: 10px;
  align-self: center;
  color: #333333;
  font-size: 16px;
  font-family: PingFang SC Bold;
  font-weight: 700;
}

.group_14 {
  margin-top: 20px;
}

.font_8 {
  font-size: 14px;
  font-family: PingFang SC Bold;
  font-weight: 700;
  color: #333333;
}

.width-100 {
  width: 100px;
}

.danhao {
  max-width: 400px;
  text-align: left;
}

.timedesc {
  max-width: 200px;
  text-align: right;
}

.group_16 {
  margin-top: 10px;
}

.text_20 {
  align-self: flex-start;
}

.font_12 {
  font-size: 14px;
  font-family: PingFang SC Bold;
  font-weight: 700;
  color: #333333;
}

.font_food {
  font-size: 14px;
  font-family: PingFang SC Bold;
  font-weight: 700;
  color: #333333;
  text-align: center;
}

.text_22 {
  margin-top: -10px;
  align-self: flex-end;
}

.group_20 {
  position: relative;
}

.group_22 {
  margin-top: 10px;
}

.space-x-12 > *:not(:first-child) {
  margin-left: 12px;
}

.group_23 {
  margin-top: 10px;
}

.space-x-46 > *:not(:first-child) {
  margin-left: 46px;
}

.text_39 {
  margin-top: 10px;
  align-self: flex-start;
}

.group_25 {
  margin-top: 12px;
  border-top: solid 1px #e2e2e2;
}

.borderTop1 {
  border-top: solid 1px #e2e2e2;
}

.food-item {
  margin-top: 10px;
}

.marginTop-10 {
  margin-top: 10px;
}

.group_29 {
  padding-top: 10px;
}

.group_30 {
  margin-top: 10px;
}

.group_32 {
  margin-top: 10px;
}

.group_33 {
  margin-top: 10px;
}

.group_34 {
  margin-top: 10px;
}

.group_38 {
  margin-top: 10px;
}

.text_64 {
  align-self: flex-start;
}

.text_66 {
  align-self: flex-end;
}

.group_39 {
  padding-top: 10px;
}

.group_40 {
  margin-top: 10px;
}

.group_41 {
  margin-top: 10px;
}

.group_44 {
  margin-top: 30px;
}

.text_74 {
  color: #333333;
  font-size: 12px;
  font-family: PingFang SC Regular;
}

.text-wrapper_21 {
  padding-top: 12px;
}

.font_6 {
  font-size: 12px;
  font-family: PingFang SC Regular;
  color: #ffffff;
}

.text_75 {
  color: #333333;
}

.section_18 {
  background: #ffffff;
  padding-top: 20px;
  border-radius: 0px 0px 12px 12px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
}

.space-x-20 > *:not(:first-child) {
  margin-left: 20px;
}

.cancel-btn {
  background-color: #ffffff;
  border-radius: 12px;
  width: 100px;
  height: 50px;
  border: solid 1px #333333;
  font-size: 18px;
  font-family: PingFang SC Regular;
  color: #333333;
  padding: 0;
}

.confirm-btn {
  background-color: #7c0a03;
  border-radius: 12px;
  width: 336px;
  height: 52px;
  font-size: 18px;
  font-family: PingFang SC Regular;
  color: #ffffff;
  border: none;
  padding: 0;
}

.confirm-btn:hover {
  background-color: #8c1a13;
}

.disabled-btn {
  background-color: #7c0a03;
  border-radius: 12px;
  width: 336px;
  height: 52px;
  font-size: 18px;
  font-family: PingFang SC Regular;
  color: #ffffff;
  border: none;
  padding: 0;
  cursor: not-allowed;
}

.print-btn {
  background-color: #ffffff;
  border-radius: 12px;
  width: 100px;
  height: 50px;
  border: solid 1px #333333;
  font-size: 18px;
  font-family: PingFang SC Regular;
  color: #333333;
  padding: 0;
}

.font-right {
  text-align: right;
}

.font-center {
  text-align: center;
}
</style>

<style lang="scss" scoped>
.pre-settlement-dialog {
  max-height: unset !important;
}

.skeleton-container {
  padding: 30px;
  width: 846px;
  box-sizing: border-box;
}
.food-list-box {
  height: 400px;
  overflow: hidden;
  overflow-y: auto;

  /* 自定义滚动条样式 */
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;

    &:hover {
      background: #a8a8a8;
    }
  }
}
</style>
